﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TelnetRouterApplication.Control;
using TelnetRouterApplication.Model;
using TelnetRouterApplication.Utils;

namespace TelnetRouterApplication.View
{
    public partial class WanSelectForm : UserControl
    {
        private MainForm _main;
        public MainForm Main
        {
            get { return _main; }
            set { _main = value; }
        }

        private List<Interface> _interfaces;
        public List<Interface> Interfaces
        {
            get { return _interfaces; }
            set { _interfaces = value; }
        }

        private Interface _actualInterface;
        public Interface ActualInterface
        {
            get { return _actualInterface; }
            set { _actualInterface = value; }
        }

        private string[] statusOptions = new string[] { "ON", "OFF" };
        private string[] clockRateOptions = new string[] { "Not Set", "1200", "2400", "4800", "9600", "19200", "38400", "5600", "6400", "72000", "125000", "128000", "148000", "250000", "500000", "800000", "1000000", "1300000", "2000000", "4000000" };

        public WanSelectForm(MainForm main)
        {
            Main = main;

            InitializeComponent();
            Interfaces = CommandHandler.GetInstance().GetInterfaces();

            wanSelectBox.Items.Insert(0, new Interface("", "", "", false, ""));
            int i = 1;
            foreach (Interface inter in Interfaces)
            {
                if (inter.Wan)
                {
                    wanSelectBox.Items.Insert(i, inter);
                    i++;
                }
            }

            statusBox.Items.AddRange(statusOptions);
            clockBox.Items.AddRange(clockRateOptions);

            if (i == 1)
            {
                MessageBox.Show("No WAN detected!");
            }
        }

        public WanSelectForm() : this(null) { }

        private void wanSelectBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            ActualInterface = (Interface)wanSelectBox.SelectedItem;
            if (!ActualInterface.Name.Equals(""))
            {
                //Preencher com os campos dessa WAN

                ActualInterface = CommandHandler.GetInstance().GetInterface(ActualInterface);
                if (MainForm.DEBUG)
                {
                    System.Diagnostics.Debug.WriteLine("Finished!");
                }
                refreshInterfaceFields(ActualInterface);
            }
        }

        private void refreshInterfaceFields(Interface inter)
        {
            if (inter.Ip.Equals("unassigned") || inter.Ip.Equals(""))
            {
                ipBox.Text = "unassigned";
                maskBox.Text = "unassigned";
            }
            else
            {
                ipBox.Text = inter.Ip;
                maskBox.Text = inter.Mask;
            }

            bool turnedOn = false;
            if (inter.IsTurnedON())
            {
                statusBox.SelectedIndex = statusBox.FindStringExact("ON");
                turnedOn = true;
            }
            else
            {
                statusBox.SelectedIndex = statusBox.FindStringExact("OFF");
            }

            int clockrate = inter.Clockrate;
            if (clockrate == 0)
            {
                clockBox.SelectedIndex = 0;
            }
            else
            {
                clockBox.SelectedIndex = clockBox.FindStringExact(clockrate + "");
            }

            if (turnedOn)
            {
                turnedPanel.BackColor = Color.Green;
            }
            else
            {
                turnedPanel.BackColor = Color.Red;
            }

            string master = "Master";

            if (!inter.Master)
            {
                master = "Slave";
            }

            nameLabel.Text = "["+master+"] "+inter.Name;
        }

        private void updateBtn_Click(object sender, EventArgs e)
        {
            if (ActualInterface.IsTurnedON() && statusBox.SelectedItem.ToString().Equals("OFF"))
            {
                CommandHandler.GetInstance().TurnInterface(false, ActualInterface);
            }
            else if (!ActualInterface.IsTurnedON() && statusBox.SelectedItem.ToString().Equals("ON"))
            {
                CommandHandler.GetInstance().TurnInterface(true, ActualInterface);
            }

            int clockrate = 0;
            if (clockBox.SelectedIndex != 0)
            {
                clockrate = int.Parse(((string)clockBox.SelectedItem));
            }
            if (ActualInterface.Clockrate != clockrate)
            {
                CommandHandler.GetInstance().ChangeInterfaceClockRate(clockrate, ActualInterface);
            }

            if (!ActualInterface.Ip.Equals(ipBox.Text) || !ActualInterface.Mask.Equals(maskBox.Text))
            {
                ActualInterface.Ip = ipBox.Text;
                ActualInterface.Mask = maskBox.Text;

                CommandHandler.GetInstance().ChangeInterfaceIP(ActualInterface);
            }

            if (MainForm.DEBUG)
            {
                System.Diagnostics.Debug.WriteLine("Apertou o botão!" + ActualInterface.IsTurnedON() + " e " + statusBox.SelectedItem.ToString());
            }

            wanSelectBox_SelectedIndexChanged(sender, e);
        }

        private void importBtn_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Import settings will replace the actual settings for the imported ones. Continue?", "Import", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                string path = IOUtils.OpenFileDialogShow(Main);
                string[] importedSettings = IOUtils.ReadTxtFile(path);

                //Na ordem é para ser
                //0- interface name
                //1- ip address
                //2- mask address
                //3- clockrate

                //Precisa fazer toda a verificação

                string[] parameters = importedSettings[1].Split('@');
                if (parameters.Length > 0)
                {
                    ipBox.Text = parameters[1];
                }
                parameters = importedSettings[2].Split('@');
                if (parameters.Length > 0)
                {
                    maskBox.Text = parameters[1];
                }
                parameters = importedSettings[3].Split('@');
                if (parameters.Length > 0)
                {
                    if (parameters[1].Equals("Not Set") || parameters[1].Equals("0"))
                    {
                        clockBox.SelectedIndex = 0;
                    }
                    else
                    {
                        int clockrate = int.Parse(parameters[1]);
                        clockBox.SelectedIndex = clockBox.FindStringExact(clockrate + "");
                    }
                }

                updateBtn_Click(sender, null);
            }
        }

        private void exportBtn_Click(object sender, EventArgs e)
        {
            //Achei desnecessário checar se o settings é nulo

            string log = "";
            log += "Interface Name@" + ActualInterface.Name + "\r\n";
            log += "Ip Address@" + ActualInterface.Ip + "\r\n";
            log += "Mask@" + ActualInterface.Mask + "\r\n";
            log += "Clock Rate@" + ActualInterface.Clockrate + "\r\n";

            string path = IOUtils.SaveFileDialogShow(Main, "Text Files|*.txt");
            IOUtils.CreateTxtFile(path, log);
            MessageBox.Show("Log exported!");
        }
    }
}
